﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using InfoPathExtractionRules;
using System.Diagnostics;

namespace IpfsWebtestAutoFixer
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            TextWriterTraceListener tl = new TextWriterTraceListener(System.Console.Error);
            Trace.Listeners.Add(tl);

            string webtestPath = null;
            string fixedWebtestPath = null;
            string invocationPath = null;

            if (args.Length > 0)
            {
                webtestPath = args[0];
            }

            if (args.Length > 1)
            {
                fixedWebtestPath = args[1];
            }

            if (args.Length > 2)
            {
                invocationPath = args[2];
            }

            if (webtestPath == null)
            {
                webtestPath = ShowOpenFileDialog();
            }

            if (!File.Exists(webtestPath))
            {
                Console.Error.WriteLine("Web test to fix " + webtestPath + " does not exist.");
                Environment.Exit(1);
            }

            if (fixedWebtestPath == null)
            {
                fixedWebtestPath = ShowSaveFileDialog();
            }

            if (string.IsNullOrEmpty(fixedWebtestPath))
            {
                Console.Error.WriteLine("Path for auto fixed web test is null or empty.");
                Environment.Exit(1);
            }

            IpfsWebTestAutoFixer fixer = new IpfsWebTestAutoFixer();
            if (invocationPath != null)
                fixer.InvocationPath = invocationPath;
            fixer.fix(webtestPath, fixedWebtestPath);
        }

        static string ShowOpenFileDialog()
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "Web Test File|*.webtest";
            openDialog.CheckFileExists = true;
            openDialog.Multiselect = false;
            openDialog.ShowDialog();

            return openDialog.FileName;
        }

        static string ShowSaveFileDialog()
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.OverwritePrompt = true;
            saveDialog.Filter = "Web Test File|*.webtest";
            saveDialog.AddExtension = true;
            saveDialog.ShowDialog();
            
            return saveDialog.FileName;
        }
    }
}
